package com.ftg.learn.assess.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.assess.entity.Media;
import com.ftg.learn.assess.mappper.MediaMapper;
import com.ftg.learn.assess.result.Result;
import com.ftg.learn.assess.service.MediaService;
import com.ftg.learn.common.constant.CodeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String MEDIA_KEY = "hiit:assess:info:";
    @Override
    public Result<List<Media>> getAssessDetail(Long evaluationId) {
        String key = MEDIA_KEY + evaluationId;
        String info = redisTemplate.opsForValue().get(key);
        if(info!=null){
            return Result.build(CodeConstant.OK,"查询成功", JSONUtil.toList(info,Media.class));
        }
        LambdaQueryWrapper<Media> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(evaluationId!=null,Media::getEvaluationId,evaluationId);
        List<Media> medias = this.baseMapper.selectList(queryWrapper);
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(medias));
        if (medias.size() == 0){
            return Result.build(200, "该评价没有数据");
        }
        return Result.build(200, "查询成功", medias);
    }

    @Override
    public void removeAssessMedia(Long evaluationId) {
        LambdaUpdateWrapper<Media> queryWrapper = Wrappers.lambdaUpdate();
        queryWrapper
                .eq(Media::getEvaluationId,evaluationId);
        this.baseMapper.delete(queryWrapper);
    }
}
